package com.wmlive.hhvideo.heihei.message;

import android.os.Handler;
import android.os.Looper;
import android.text.TextUtils;

import com.google.gson.Gson;
import com.wmlive.hhvideo.application.DCApplication;
import com.wmlive.hhvideo.common.GlobalParams;
import com.wmlive.hhvideo.heihei.beans.message.IMMessageBean;
import com.wmlive.hhvideo.heihei.db.datatable.IMMessageDefaultTable;
import com.wmlive.hhvideo.heihei.db.datatable.IMMessageUserTable;
import com.wmlive.hhvideo.heihei.db.manager.IMMessageDefaultDBManager;
import com.wmlive.hhvideo.heihei.db.manager.IMMessageUserDBManager;
import com.wmlive.hhvideo.heihei.login.AccountUtil;
import com.wmlive.hhvideo.utils.KLog;


import java.util.concurrent.BlockingDeque;
import java.util.concurrent.LinkedBlockingDeque;

import cn.wmlive.hhvideo.rxbuslib.RxBus2;

/**
 * IM 的消息分发
 * Created by kangzhen on 2017/7/6.
 */

public class IMMessageDispatcher {
    public static final String TAG = "IMMessageDispatcher";
    private static IMMessageDispatcher mIMMessageDispatcher;

    private static final BlockingDeque<IMMessage> imMessageQueue = new LinkedBlockingDeque<>();

    private static Handler imMessageHandler;
    private Object mObject =new Object();

    public static IMMessageDispatcher getInstance() {
        KLog.e(TAG,"----------create-------getInstance----");
        if (mIMMessageDispatcher == null) {
            synchronized (IMMessageDispatcher.class) {
                if (mIMMessageDispatcher == null) {
                    mIMMessageDispatcher = new IMMessageDispatcher();
                }
            }
        }
        return mIMMessageDispatcher;
    }

    public IMMessageDispatcher() {
        KLog.e(TAG,"----------create-------IMMessageDispatcher----");
        imMessageHandler = new Handler(Looper.getMainLooper());
        imMessageHandler.post(actionIMMessageRunnable);

    }

    /**
     * 销毁
     */
    public void onDestroy() {
        try {
            KLog.e(TAG,"-----------------onDestroy------------");
            mIMMessageDispatcher = null;
            imMessageQueue.clear();
            imMessageHandler.removeCallbacksAndMessages(null);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
        }
    }
    /**
     * Im 消息runnable
     */
    private Runnable actionIMMessageRunnable = new Runnable() {

        @Override
        public void run() {
            if (!imMessageQueue.isEmpty()) {
                synchronized (mObject) {
                    packagIMMessageData(imMessageQueue.peek());
                    imMessageQueue.poll();
                }
            }
            imMessageHandler.postDelayed(this, 150L);
        }
    };

    /**
     * 添加IM 消息到对垒
     * @param messages
     */
    public synchronized void addIMMessgeToQuene(IMMessage messages) {
        KLog.i(TAG,"-----addIMMessgeToQuene-----------start-------");
        imMessageQueue.add(messages);
        KLog.e(TAG,"-----------------imMessageQueue------size-------------:"+imMessageQueue.size());
        KLog.i(TAG,"-----addIMMessgeToQuene-------end------------");
    }
    /**
     * 封装IM数据
     * @param message
     */
    private synchronized  void  packagIMMessageData(IMMessage message) {
        KLog.i(TAG,"-----packagIMMessageData--------------:"+message.getContent_mssage());
        try {
            if(message==null || TextUtils.isEmpty(message.getContent_mssage())){
                    return;
            }
            Gson mGson = new Gson();
            String strContent_message = message.getContent_mssage();
            IMMessageBean mImMsgBean = null ;
            //IM中消息体部分
            if (!TextUtils.isEmpty(strContent_message)) {
                mImMsgBean = mGson.fromJson(strContent_message, IMMessageBean.class);
            }
           if(AccountUtil.getUserId()>0 && !TextUtils.isEmpty(AccountUtil.getToken()) && mImMsgBean!=null){
                //处于用户登录状态
               KLog.i(TAG,"----has datas-------packagIMMessageData-------userId:"+AccountUtil.getUserId()+"------count------:"+IMMessageUserDBManager.getInstance(DCApplication.getDCApp()).getIMMessageAllCount());

               IMMessageUserTable imMessageUserEntry = mImMsgBean.IMMessageBeanToIMMessageUserEntry();
               IMMessageUserDBManager.getInstance(DCApplication.getDCApp()).saveIMUserData(imMessageUserEntry);
               KLog.i(TAG,"----add datas-------packagIMMessageData-------userId:"+AccountUtil.getUserId()+"------------end");
               //发送有新消息通知
               RxBus2.get().send(GlobalParams.RXBusCode.IM_NOTIFICATION_NEW_MSG);
           }else{
               KLog.i(TAG,"-----------packagIMMessageData-------default");
               KLog.i(TAG,"-----has datas ------packagIMMessageData-------default---the count:"+IMMessageDefaultDBManager.getInstance(DCApplication.getDCApp()).getIMMessageAllCount());

               IMMessageDefaultTable imMessageDefaultEntry = mImMsgBean.IMMessageBeanToIMMessageDefaultEntry();
               long iResult= IMMessageDefaultDBManager.getInstance(DCApplication.getDCApp()).saveIMDefaultData(imMessageDefaultEntry);
               KLog.i(TAG,"---add datas--------packagIMMessageData-------default-----iResult------:"+iResult);
               //发送有新消息通知
               RxBus2.get().send(GlobalParams.RXBusCode.IM_NOTIFICATION_NEW_MSG);
           }
        } catch (Exception e) {
            KLog.e(TAG,"-----------packagIMMessageData-------Exception："+e.getMessage());
        }
    }
}
